package com.sky.Aspect;

import com.sky.Annotation.AutoFill;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /*
      切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.Annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    //前置通知
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动填充开始");
        //获取拦截方法上的操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();
        Object[] args = joinPoint.getArgs();
        if (args.length < 1) {
            return;
        }
        Object as = args;
        System.out.println(as.getClass().getName());
        //根据操作类型进行相应的填充操作
//        if (value == OperationType.INSERT){
//            Method setCreateTime = args.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
//            setCreateTime.invoke(as, LocalDateTime.now());
//            Method setUpdateTime = args.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
//            setUpdateTime.invoke(as, LocalDateTime.now());
//            Method setCreateUser = args.getClass().getDeclaredMethod("setCreateUser", Long.class);
//            setCreateUser.invoke(as, 1L);
//            Method setUpdateUser = args.getClass().getDeclaredMethod("setUpdateUser", Long.class);
//            setUpdateUser.invoke(as, 1L);
//        }else {
//            Method setUpdateTime = args.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
//            setUpdateTime.invoke(as, LocalDateTime.now());
//            Method setUpdateUser = args.getClass().getDeclaredMethod("setUpdateUser", Long.class);
//            setUpdateUser.invoke(as, 1L);
//        }
    }

}
